package com.liaoye.hellocustomview.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

import com.liaoye.hellocustomview.R;

/**
 * 不规则头像
 */
public class AvatorView extends View {

    private Paint mPaint;
    private Bitmap mBitmap;
    private BitmapShader mBitmapShader;

    public AvatorView(Context context) {
        super(context);
        init();
    }

    public AvatorView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public AvatorView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        setLayerType(LAYER_TYPE_SOFTWARE, null);
        //设置画笔的基本属性
        mPaint = new Paint();

        mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.avator);
        mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);


        Matrix matrix = new Matrix();
        float scaleX = getWidth() / mBitmap.getWidth();
        float scaleY = getHeight() / mBitmap.getHeight();
        matrix.setScale(scaleX, scaleY);
        mBitmapShader.setLocalMatrix(matrix);


        mPaint.setShader(mBitmapShader);

        float half = getWidth() / 2;
        canvas.drawCircle(half, half, getWidth() / 2, mPaint);


    }
}
